#!/bin/bash

# Default configuration
clean="n"
release="n"
cross_compile="n"
cross_host=""
bear="n"
enable_mqtt_test="n"
target="all"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 最外围编译脚本
# 用于构建整个项目，包括所有库和可执行文件

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# 默认参数
BUILD_TYPE="native"
CROSS_HOST=""
CLEAN_BUILD="n"
BUILD_TARGET="all"
USE_BEAR="n"
ENABLE_MQTT_TEST="n"

show_help() {
    cat << EOF
Usage: $0 [OPTIONS]

Options:
    --cross-compile         Enable cross compilation
    --host HOST             Set host for cross compilation (e.g., arm-linux-gnueabihf)
    --clean                 Clean build artifacts before building
    --target TARGET         Set build target (all, main, example_mqtt, example_log, test_mqtt, test_log)
    --bear                  Use bear to generate compile_commands.json
    --help                  Show this help message

Examples:
    # Native compilation of all targets
    ./build.sh

    # Cross compilation for ARM
    ./build.sh --cross-compile --host arm-linux-gnueabihf
    
    # Clean build
    ./build.sh --clean
    
    # Build only main target
    ./build.sh --target main
    
    # Generate compile_commands.json with bear
    ./build.sh --bear
EOF
}

# 解析参数
while [[ $# -gt 0 ]]; do
    case $1 in
        --cross-compile)
            BUILD_TYPE="cross"
            shift
            ;;
        --host)
            CROSS_HOST="$2"
            shift 2
            ;;
        --clean)
            CLEAN_BUILD="y"
            shift
            ;;
        --target)
            BUILD_TARGET="$2"
            shift 2
            ;;
        --bear)
            USE_BEAR="y"
            shift
            ;;
        --help)
            show_help
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            show_help
            exit 1
            ;;
    esac
done

# 写入配置到 config.mk
write_config() {
    echo "Writing configuration to src/lib/config.mk..."
    
    # 创建配置内容
    cat > "$SCRIPT_DIR/src/lib/config.mk" << EOF
# Auto-generated configuration file
# Generated by build.sh on $(date)

# Build type configuration
CONFIG_BUILD_TYPE = debug

# MQTT support
CONFIG_MQTT = y

# Cross compilation settings
CONFIG_CROSS_COMPILE = $([ "$BUILD_TYPE" = "cross" ] && echo "y" || echo "n")
CONFIG_CROSS_HOST = $CROSS_HOST

# MQTT test settings
CONFIG_ENABLE_MQTT_TEST = $([ "$ENABLE_MQTT_TEST" = "y" ] && echo "y" || echo "n")
EOF
}

# 清理构建产物
clean_build() {
    echo "Cleaning build artifacts..."
    make -C "$SCRIPT_DIR" clean
}

# 构建项目
build_project() {
    echo "Building project with target: $BUILD_TARGET"
    
    # 构建命令
    BUILD_CMD="make -C \"$SCRIPT_DIR\" $BUILD_TARGET"
    
    # 如果使用bear工具
    if [ "$USE_BEAR" = "y" ]; then
        if ! command -v bear &> /dev/null; then
            echo "Error: bear not found. Please install bear to generate compile_commands.json"
            exit 1
        fi
        BUILD_CMD="bear -- $BUILD_CMD"
        echo "Using bear to generate compile_commands.json"
    fi
    
    # 如果是交叉编译，添加相关参数
    if [ "$BUILD_TYPE" = "cross" ]; then
        if [ -z "$CROSS_HOST" ]; then
            echo "Error: --host is required for cross-compilation"
            exit 1
        fi
        echo "Cross-compiling for host: $CROSS_HOST"
    fi
    
    echo "Executing: $BUILD_CMD"
    eval $BUILD_CMD
    
    if [ $? -eq 0 ]; then
        echo "Build completed successfully!"
        return 0
    else
        echo "Build failed!"
        return 1
    fi
}

# 主函数
main() {
    echo "LW100_R31 Build Script"
    echo "======================"
    echo "Build type: $BUILD_TYPE"
    [ "$BUILD_TYPE" = "cross" ] && echo "Cross host: $CROSS_HOST"
    echo "Clean build: $([ "$CLEAN_BUILD" = "y" ] && echo "yes" || echo "no")"
    echo "Build target: $BUILD_TARGET"
    echo "Use bear: $([ "$USE_BEAR" = "y" ] && echo "yes" || echo "no")"
    echo ""
    
    # 写入配置
    write_config
    
    # 如果需要清理，先清理
    if [ "$CLEAN_BUILD" = "y" ]; then
        clean_build
    fi
    
    # 构建项目
    if build_project; then
        echo ""
        echo "Build Summary:"
        echo "--------------"
        echo "Successfully built target '$BUILD_TARGET'"
        [ "$USE_BEAR" = "y" ] && echo "Generated compile_commands.json for IDE integration"
        echo "Executable files are located in the 'build/' directory"
        echo ""
        echo "To run the main application:"
        echo "  LD_LIBRARY_PATH=build:src/lib/com_lib ./build/main"
        echo ""
        echo "To run the MQTT example:"
        echo "  LD_LIBRARY_PATH=build:src/lib/com_lib ./build/example_mqtt"
        echo ""
        echo "To run the log example:"
        echo "  LD_LIBRARY_PATH=build:src/lib/com_lib ./build/example_log"
    else
        echo ""
        echo "Build failed. Please check the error messages above."
        exit 1
    fi
}

# 执行主函数
main "$@"